//
//  socket.swift
//  AlterationSwitch
//
//  Created by solarke_apple_mini_1 on 2018/10/29.
//  Copyright © 2018年 石家庄科林电气股份有限公司. All rights reserved.
//

import UIKit

var socketClient:TCPClient?

//初始化客户端，并连接服务器
public func processClientSocket() {
    socketClient=TCPClient(addr: "192.168.0.1", port: 2020)
    DispatchQueue.global(qos: .background).async {
        //用于读取并解析服务端发来的消息
        func readmsg() -> [UInt8]?{
            let buff = socketClient!.readAll()
            return buff
        }
        
        //连接服务器
        let (success,msg) = socketClient!.connect(timeout: 10000)
        if success{
            DispatchQueue.main.async {
                showToast("设备连接成功！")
            }
            
            //不断接收服务器发来的消息
            while true{
                if let msg=readmsg() {
                    DispatchQueue.main.async {
                        processMessage(msg: msg)
                    }
                }else{
                    DispatchQueue.main.async {
                        //self.disconnect()
                    }
                    break
                }
            }
        }else{
            DispatchQueue.main.async {
                showToast(msg)
            }
        }
    }
}

public func sendMessageBytes(msg:[UInt8]) {
    let isTrue = socketClient?.send(data: msg)
    print("isTrueisTrue-->\(String(describing: isTrue))")
}

//处理服务器返回的消息
func processMessage(msg:[UInt8]){
    let point:UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>.allocate(capacity: msg.count)
    
    for i in 0..<msg.count {
        point[i] = msg[i]
    }
    let process = ocFile().parse_recv_frame(point)
    let pro = getDictionaryFromJSONString(jsonString: process)
    let type = pro["type"] as! Int
    let data = pro["data"] as AnyObject
    print("type-->\(type)")
    print("data-->\(data)")
    switch type {
    case 1:
        notificationCenter.post(name: huanXiangControlNotification, object: nil, userInfo: ["data":data])
    case 786447:
        notificationCenter.post(name: CommutationSwitchOnlineNotification, object: nil, userInfo: ["data":data])
    case 786611:
        notificationCenter.post(name: VoltageCurrentNotification, object: nil, userInfo: ["data":data])
    case 786613:
        notificationCenter.post(name: CommutationSwitchDataNotification, object: nil, userInfo: ["data":data])
    case 852207:
        notificationCenter.post(name: DayFrozenSwitchNumberNotification, object: nil, userInfo: ["data":data])
    case 852208:
        notificationCenter.post(name: MonthFrozenSwitchNumberNotification, object: nil, userInfo: ["data":data])
    default:
        break
    }
    
    
    
}
